<?php

namespace App\Http\Controllers;

use App\Models\Member;
use App\Http\Requests\LoginRequest as Request;
use Iamxcd\LaravelCRUD\Traits\HasResponse;
use Illuminate\Support\Facades\Hash;

class loginController extends Controller
{
    use HasResponse;

    public function login(Request $request)
    {
        $data = $request->validated();

        $member = Member::query()->where('account', $data['account'])->first();

        if (is_null($member) || !Hash::check($data['password'], $member->password)) {
            return $this->responseError('账户名或密码错误');
        }

        return $this->response([
            'token' => $member->createToken($member->id)->plainTextToken
        ]);
    }

    public function register(Request $request)
    {
        $data = $request->validated();
        Member::query()->create([
            'account' => $data['account'],
            'password' => bcrypt($data['password'])
        ]);
        return $this->responseMessage('注册成功');
    }
}
